package ar.edu.utn.frgp.labtec.interceptors;

import ar.edu.utn.frgp.labtec.actions.BaseAction;
import ar.edu.utn.frgp.labtec.actions.LoginAction;
import ar.edu.utn.frgp.labtec.entities.Usuario;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

@SuppressWarnings("serial")
public class InterAutenticacion implements Interceptor {

	public void destroy() { }
	public void init() { }
  
	public String intercept(ActionInvocation actionInvocation) throws Exception {
  
		Usuario usuario = (Usuario) ActionContext.getContext().getSession().get("usuario");
		Action action = (Action)actionInvocation.getAction();
		String result = Action.LOGIN;
		
		if(action instanceof BaseAction){
			if(validarVisibilidad(usuario, action) || action instanceof LoginAction)
				result = actionInvocation.invoke();
			else{
				result = Action.LOGIN;
				((BaseAction)action).addActionError("El usuario no tiene permiso");
			}
		}else{
			result = Action.LOGIN;
		}
		
		return result;
	}
	
	private Boolean validarVisibilidad(Usuario usuario, Action action){
		try {
			  BaseAction labtecAction = (BaseAction) action;
			  if(labtecAction.getPermisos().contains(usuario.getPermiso()))
				  return true;
			  else
				  return false;
		} catch (Exception e) {
			return false;
		}
	}
}
